<script setup>
import { ref, onMounted } from "vue";
import {
  queryRoomPageApi,
  addRoomApi,
  queryRoomByIdApi,
  updateRoomApi,
  deleteRoomApi,
} from "@/api/room";
import { queryBuildingAllApi } from "@/api/building";
import { ElMessage, ElMessageBox } from "element-plus";

// 房间类型、状态下拉
const roomTypes = [
  { name: "单人间", value: 1 },
  { name: "双人间", value: 2 },
  { name: "四人间", value: 3 },
  { name: "六人间", value: 4 },
];
const roomStatus = [
  { name: "空闲", value: 1 },
  { name: "已满", value: 2 },
  { name: "维修中", value: 3 },
  { name: "停用", value: 0 },
];

// 楼栋下拉
const buildingList = ref([]);
const fetchBuildingList = async () => {
  const res = await queryBuildingAllApi();
  if (res.code) {
    buildingList.value = res.data;
  }
};

// 查询表单
const searchForm = ref({ buildingId: "", roomNo: "", type: "", status: "" });

// 房间列表、分页
const roomList = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

const fetchRoomList = async () => {
  const params = {
    buildingId: searchForm.value.buildingId,
    roomNo: searchForm.value.roomNo,
    type: searchForm.value.type,
    status: searchForm.value.status,
    page: currentPage.value,
    pageSize: pageSize.value,
  };
  const res = await queryRoomPageApi(params);
  if (res.code) {
    roomList.value = res.data.records;
    total.value = res.data.total;
  }
};

onMounted(() => {
  fetchBuildingList();
  fetchRoomList();
});

const handleSizeChange = () => fetchRoomList();
const handleCurrentChange = () => fetchRoomList();
const clear = () => {
  searchForm.value = { buildingId: "", roomNo: "", type: "", status: "" };
  fetchRoomList();
};

// 弹窗表单
const dialogVisible = ref(false);
const dialogTitle = ref("新增房间");
const roomForm = ref({
  buildingId: "",
  roomNo: "",
  type: "",
  bedCount: 1,
  facility: "",
  status: 1,
  remark: "",
});
const roomFormRef = ref();

const openAdd = () => {
  dialogTitle.value = "新增房间";
  dialogVisible.value = true;
  roomForm.value = { buildingId: "", roomNo: "", type: "", bedCount: 1, facility: "", status: 1, remark: "" };
  if (roomFormRef.value) roomFormRef.value.resetFields();
};

const openEdit = async (row) => {
  dialogTitle.value = "编辑房间";
  dialogVisible.value = true;
  const res = await queryRoomByIdApi(row.id);
  if (res.code) {
    roomForm.value = { ...res.data };
  }
};

const saveRoom = () => {
  roomFormRef.value.validate(async (valid) => {
    if (!valid) return ElMessage.error("表单校验不通过");
    let res;
    if (roomForm.value.id) {
      res = await updateRoomApi(roomForm.value);
    } else {
      res = await addRoomApi(roomForm.value);
    }
    if (res.code) {
      ElMessage.success("保存成功");
      dialogVisible.value = false;
      fetchRoomList();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const handleDelete = (row) => {
  ElMessageBox.confirm("确定要删除该房间吗？", "提示", { type: "warning" })
    .then(async () => {
      const res = await deleteRoomApi(row.id);
      if (res.code) {
        ElMessage.success("删除成功");
        fetchRoomList();
      } else {
        ElMessage.error(res.msg);
      }
    })
    .catch(() => {});
};

// 表单校验规则
const rules = {
  buildingId: [{ required: true, message: "请选择楼栋", trigger: "change" }],
  roomNo: [{ required: true, message: "请输入房间号", trigger: "blur" }],
  type: [{ required: true, message: "请选择房间类型", trigger: "change" }],
  bedCount: [{ required: true, message: "请输入床位数", trigger: "blur" }],
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
};
</script>

<template>
  <div>
    <!-- 查询表单 -->
    <el-form :inline="true" :model="searchForm" class="demo-form-inline" style="margin-bottom: 16px">
      <el-form-item label="楼栋">
        <el-select v-model="searchForm.buildingId" placeholder="请选择楼栋" clearable>
          <el-option v-for="b in buildingList" :key="b.id" :label="b.name" :value="b.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="房间号">
        <el-input v-model="searchForm.roomNo" placeholder="请输入房间号" clearable />
      </el-form-item>
      <el-form-item label="类型">
        <el-select v-model="searchForm.type" placeholder="请选择类型" clearable>
          <el-option v-for="t in roomTypes" :key="t.value" :label="t.name" :value="t.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
          <el-option v-for="s in roomStatus" :key="s.value" :label="s.name" :value="s.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchRoomList">查询</el-button>
        <el-button @click="clear">重置</el-button>
      </el-form-item>
      <el-form-item style="float:right; margin-left:auto;">
        <el-button type="primary" @click="openAdd">+ 新增房间</el-button>
      </el-form-item>
    </el-form>

    <!-- 房间表格 -->
    <el-table :data="roomList" border stripe style="width: 100%">
      <el-table-column prop="id" label="ID" width="60" />
      <el-table-column prop="buildingName" label="楼栋" />
      <el-table-column prop="roomNo" label="房间号" />
      <el-table-column prop="type" label="类型">
        <template #default="scope">
          {{ roomTypes.find(t => t.value === scope.row.type)?.name || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="bedCount" label="床位数" />
      <el-table-column prop="facility" label="设施" />
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : scope.row.status === 2 ? 'danger' : scope.row.status === 3 ? 'warning' : 'info'">
            {{ roomStatus.find(s => s.value === scope.row.status)?.name || '-' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" />
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" @click="openEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :total="total"
      :page-sizes="[5, 10, 20, 50]"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      style="margin-top: 16px; text-align: right;"
    />

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" @close="roomFormRef?.resetFields()">
      <el-form :model="roomForm" :rules="rules" ref="roomFormRef" label-width="100px">
        <el-form-item label="楼栋" prop="buildingId">
          <el-select v-model="roomForm.buildingId" placeholder="请选择楼栋">
            <el-option v-for="b in buildingList" :key="b.id" :label="b.name" :value="b.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="房间号" prop="roomNo">
          <el-input v-model="roomForm.roomNo" placeholder="请输入房间号" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="roomForm.type" placeholder="请选择类型">
            <el-option v-for="t in roomTypes" :key="t.value" :label="t.name" :value="t.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="床位数" prop="bedCount">
          <el-input-number v-model="roomForm.bedCount" :min="1" :max="20" />
        </el-form-item>
        <el-form-item label="设施" prop="facility">
          <el-input v-model="roomForm.facility" placeholder="请输入设施描述" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="roomForm.status" placeholder="请选择状态">
            <el-option v-for="s in roomStatus" :key="s.value" :label="s.name" :value="s.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="roomForm.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveRoom">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.demo-form-inline {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}
</style> 